import React, { useState, useEffect, useRef } from 'react'

export const useTime = () => {
  const [canSend, setCanSend] = useState(true)
  const [count, setCount] = useState(0)
  const [countText, setCountText] = useState('获取验证码')
  const timerId = useRef()
  useEffect(() => {
    // 销毁
    return () => {
      clearInterval(timerId.current)
    }
  }, [])
  useEffect(() => {
    if (count === 0) {
      //  清除定时器+恢复初始值
      // setCount(5)
      setCanSend(true)
      setCountText('获取验证码')
      clearInterval(timerId.current)
    } else {
      setCountText(count + '秒后发送')
    }
  }, [count])
  // 定义点击事件函数
  const send = (n) => {
    setCanSend(false)
    setCount(n)
    // {canSend ? '发送验证码' : count + '秒后发送'}
    // setCountText(count + '秒后发送')

    timerId.current = setInterval(() => {
      setCount((preCount) => {
        console.log(preCount, 88)

        return preCount - 1
      }) // 这种写法有什么问题 //59
    }, 1000)
  }

  return { count, send, canSend, countText }
}
